package com.example.gray.controller;


import com.example.gray.entity.Result;
import com.example.gray.entity.User;
import com.example.gray.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * @author Lord
 * @date 2021/12/27 14:49
 */
@RestController
@CrossOrigin
@RequestMapping(value = "/user")
@Api(tags = "用户")
public class HelloWorld {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录")
    @PostMapping(value = "login")
    public Object login(@RequestBody User user){
        User user2 = userService.getUser(user.getName());
        if (user2 != null&&user.getPassword().equals(user2.getPassword())) {
            return Result.success("登录成功");
        }else {
            return Result.error(4001,"用户名或密码错误","");
        }
    }

    @ApiOperation(value = "查找用户")
    @GetMapping(value = "search")
    public Object search(String name){
        User user = userService.getUser(name);
        return Result.success(user);
    }

    @ApiOperation(value = "插入用户")
    @PostMapping(value = "insert")
    public Object insert(String name,String password){
        User user = new User(1,name,password,1);
        if (userService.insertUser(user) == 1){
            return Result.success("插入成功");
        }
        else {
            return Result.error(4001,"插入失败","请联系后端工程师");
        }
    }

    @ApiOperation(value = "删除用户")
    @PostMapping(value = "delete")
    public Object delete(Integer id){
        if (userService.deleteUser(id) == 1) {
            return Result.success("删除成功");
        }else {
            return Result.error(4001,"操作失败","");
        }
    }

    @ApiOperation(value = "修改密码")
    @PostMapping(value = "updatePassword")
    public Object update(Integer id,String password){
        User user = new User(id,"",password,0);
        if (userService.updateUser(user) == 1){
            return Result.success("修改成功");
        }
        else {
            return Result.error(4001,"修改失败","");
        }
    }
}
